package com.lnw.controller;

import com.lnw.entity.Province;
import com.lnw.entity.Result;
import com.lnw.service.ProvinceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("province")
public class ProvinceController {

    @Autowired
    private ProvinceService provinceService;

    @GetMapping("findByPage")
    public Map<String,Object>  findByPage(Integer page,Integer rows){
        page = page==null?1:page;
        rows = rows==null?4:rows;
        HashMap<String, Object> map = new HashMap<>();
        //分页处理
        List<Province> provinceList = provinceService.findByPage(page, rows);
        //计算总页数
        Integer totals = provinceService.findTotals();
        Integer totalPage = totals%rows==0?totals/rows:totals/rows+1;
        map.put("province",provinceList);
        map.put("totals",totals);
        map.put("totalPage",totalPage);
        map.put("page",page);
        return map;
    }

    /**
     * 保存省份
     * @param province
     * @return
     */
    @PostMapping("save")
    public Result save(@RequestBody Province province){
        Result result = new Result();
        try{
            provinceService.save(province);
            result.setMsg("保存省份成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg("保存省份失败");
        }

        return result;
    }

    /**
     * 删除省份
     * @param id
     * @return
     */
    @GetMapping("delete")
    public Result delete(String id){
        Result result = new Result();
        try{
            provinceService.delete(id);
            result.setMsg("删除省份成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg("删除省份失败");
        }

        return result;
    }

    @PostMapping("update")
    public Result update(@RequestBody Province province){
        Result result = new Result();
        try{
            provinceService.update(province);
            result.setMsg("修改省份成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setStatus(false).setMsg("修改省份失败");
        }

        return result;
    }

    @GetMapping("findOne")
    public Province findOne(String id){
        return provinceService.findOneProvince(id);
    }
}
